/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.DateUtils;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.func.MetaFuncRpcService;
import com.je.rbac.exception.RoleException;
import com.je.rbac.service.grant.DevelopPlatformService;
import com.je.rbac.service.grant.develop.RbacGrantDevelopMenuPermmisionService;
import com.je.rbac.service.grant.develop.RbacGrantDevelopPcFuncButtonPermmisionService;
import com.je.rbac.service.grant.develop.RbacGrantDevelopPcFuncPermmisionService;
import com.je.rbac.service.grant.develop.RbacGrantDevelopPluginPermissionService;
import com.je.rbac.service.permission.GrantTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.je.rbac.service.role.impl.RbacRoleServiceImpl.ROLE_TYPE_CODE;
import static com.je.rbac.service.role.impl.RbacRoleServiceImpl.ROLE_TYPE_NAME;

@Service
public class DevelopPlatformServiceImpl implements DevelopPlatformService {

    public static final String DEV_KEY = "PLATFORM_DEVELOP";

    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaResourceService metaResourceService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private RbacGrantDevelopMenuPermmisionService rbacGrantDevelopMenuPermmisionService;
    @Autowired
    private RbacGrantDevelopPcFuncPermmisionService rbacGrantDevelopPcFuncPermmisionService;
    @Autowired
    private RbacGrantDevelopPcFuncButtonPermmisionService rbacGrantDevelopPcFuncButtonPermmisionService;
    @Autowired
    private RbacGrantDevelopPluginPermissionService rbacGrantDevelopPluginPermissionService;
    @Autowired
    private MetaFuncRpcService metaFuncRpcService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public DynaBean createPlatfromRole(String roleId) {
        String devRoleId = systemSettingRpcService.findSettingValue(DEV_KEY);
        if(!Strings.isNullOrEmpty(devRoleId)){
            return metaService.selectOne("JE_RBAC_ROLE",ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID",devRoleId));
        }

        if(Strings.isNullOrEmpty(roleId)){
            roleId = DEV_ID;
        }

        List<Map<String,Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ROLE");
        int count = (int) countList.get(0).get("MAX_COUNT");
        List<Map<String,Object>> currentChildList = metaService.selectSql("SELECT COUNT(*) AS TOTAL_COUNT FROM JE_RBAC_ROLE WHERE SY_PARENT = {0}","ROOT");
        long currentChildCount = (long) currentChildList.get(0).get("TOTAL_COUNT");
        DynaBean roleBean = new DynaBean("JE_RBAC_ROLE", false);
        roleBean.set("JE_RBAC_ROLE_ID", roleId);
        roleBean.set("ROLE_NAME", DEV_NAME);
        roleBean.set("ROLE_CODE", "role-" + String.format("%06d", count+1));
        roleBean.set("ROLE_TYPE_CODE", ROLE_TYPE_CODE);
        roleBean.set("ROLE_TYPE_NAME", ROLE_TYPE_NAME);

        //树形节点值
        roleBean.set("SY_PARENT", "ROOT");
        roleBean.set("SY_PARENTPATH", "/ROOT");
        roleBean.set("SY_LAYER",  1);
        roleBean.set("SY_STATUS", "1");
        roleBean.set("SY_NODETYPE", "LEAF");
        roleBean.set("SY_PATH", "/ROOT" + "/" + roleId);
        roleBean.set("SY_TREEORDERINDEX", "000001" + String.format("%06d", currentChildCount+1));
        //创建时间
        roleBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
        roleBean.set("ROLE_DEVELOP", "1");
        roleBean.set("SY_ORDERINDEX",count+1);
        commonService.buildModelCreateInfo(roleBean);
        metaService.insert(roleBean);
        systemSettingRpcService.writeValue("_CUSTON",DEV_KEY,roleId);
        return roleBean;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void grant(String roleId) throws RoleException {
        String devRoleId = systemSettingRpcService.findSettingValue(DEV_KEY);
        if(Strings.isNullOrEmpty(roleId)){
            roleId = devRoleId;
        }
        List<DynaBean> platformProductBeanList = metaResourceService.selectByTableCodeAndNativeQuery("JE_PRODUCT_MANAGE", NativeQuery.build()
                .eq("PRODUCT_TYPE", "2"));
        List<String> productIdList = new ArrayList<>();
        for (DynaBean eachProductBean : platformProductBeanList) {
            productIdList.add(eachProductBean.getStr("JE_PRODUCT_MANAGE_ID"));
        }
        List<DynaBean> menuBeanList = metaService.select("JE_CORE_MENU",ConditionsWrapper.builder().in("SY_PRODUCT_ID",productIdList));
        List<String> menuIdList = new ArrayList<>();
        Map<String, Boolean> pluginMap = new HashMap<>();
        List<String> funcCodeList = new ArrayList<>();
        for (DynaBean eachMenuBean : menuBeanList) {
            menuIdList.add(eachMenuBean.getStr("JE_CORE_MENU_ID"));
            if (!"MENU".equals(eachMenuBean.getStr("MENU_NODEINFOTYPE"))
                    && !"MT".equals(eachMenuBean.getStr("MENU_NODEINFOTYPE"))) {
                pluginMap.put(eachMenuBean.getStr("MENU_NODEINFO"), true);
            }
            if("MT".equals(eachMenuBean.getStr("MENU_NODEINFOTYPE"))){
                funcCodeList.add(eachMenuBean.getStr("MENU_NODEINFO"));
            }
        }

        //功能
        Map<String, List<DynaBean>> funcResult = metaFuncRpcService.findPermedFuncsAndChildFuncsWithButtonsByFuncCodes(funcCodeList);
        List<DynaBean> funcMainList = new ArrayList<>();
        funcMainList.addAll(funcResult.get("main"));
        List<DynaBean> funcChildList = new ArrayList<>();
        funcChildList.addAll(funcResult.get("child"));
        //按钮
        List<DynaBean> funcButtonList = funcResult.get("button") == null ? new ArrayList<>() : funcResult.get("button");

        Map<String, List<String>> funcButtonMap = new HashMap<>();
        List<String> buttonList;
        //主功能授权、子功能授权
        for (DynaBean eachFuncBean : funcMainList) {
            if (!funcButtonMap.containsKey(eachFuncBean.getStr("FUNCINFO_FUNCCODE"))) {
                buttonList = new ArrayList<>();
                funcButtonMap.put(eachFuncBean.getStr("FUNCINFO_FUNCCODE"), buttonList);
            } else {
                buttonList = funcButtonMap.get(eachFuncBean.getStr("FUNCINFO_FUNCCODE"));
            }

            for (DynaBean eachButtonBean : funcButtonList) {
                if (!eachFuncBean.getStr("JE_CORE_FUNCINFO_ID").equals(eachButtonBean.getStr("RESOURCEBUTTON_FUNCINFO_ID"))) {
                    continue;
                }
                buttonList.add(eachButtonBean.getStr("RESOURCEBUTTON_CODE"));
            }
        }
        for (DynaBean eachFuncBean : funcChildList) {
            if (!funcButtonMap.containsKey(eachFuncBean.getStr("FUNCRELATION_CODE"))) {
                buttonList = new ArrayList<>();
                funcButtonMap.put(eachFuncBean.getStr("FUNCRELATION_CODE"), buttonList);
            } else {
                buttonList = funcButtonMap.get(eachFuncBean.getStr("FUNCRELATION_CODE"));
            }

            for (DynaBean eachButtonBean : funcButtonList) {
                if (!eachFuncBean.getStr("FUNCRELATION_FUNCINFO_ID").equals(eachButtonBean.getStr("RESOURCEBUTTON_FUNCINFO_ID"))) {
                    continue;
                }
                buttonList.add(eachButtonBean.getStr("RESOURCEBUTTON_CODE"));
            }
        }
        //插件
        rbacGrantDevelopPluginPermissionService.saveDevelopPluginPermissions(roleId,pluginMap, GrantTypeEnum.MENU);
        //菜单
        rbacGrantDevelopMenuPermmisionService.saveDevelopMenuPermissions(roleId, menuIdList, GrantTypeEnum.MENU);
        //功能&功能按钮
        for (String eachFuncCode : funcButtonMap.keySet()) {
            rbacGrantDevelopPcFuncPermmisionService.saveDevelopFuncShowPermission(roleId,eachFuncCode,GrantTypeEnum.MENU);
            if(roleId.equals(devRoleId)){
                rbacGrantDevelopPcFuncPermmisionService.saveDevelopFuncConfigPermission(roleId,eachFuncCode,GrantTypeEnum.MENU);
            }
            rbacGrantDevelopPcFuncButtonPermmisionService.saveDevelopFuncButtonShowPermission(roleId,eachFuncCode,funcButtonMap.get(eachFuncCode),GrantTypeEnum.MENU);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void assignPlatformRoleUser(String accountId) throws RoleException {
        String devRoleId = systemSettingRpcService.findSettingValue(DEV_KEY);
        if(Strings.isNullOrEmpty(devRoleId)){
            throw new RoleException("请初始化平台开发人员");
        }

        List<DynaBean> accountDeptBeanList = metaService.select("JE_RBAC_ACCOUNTDEPT",ConditionsWrapper.builder()
                .eq("ACCOUNTDEPT_ACCOUNT_ID",accountId));
        if(accountDeptBeanList == null || accountDeptBeanList.isEmpty()){
            throw new RoleException("账号未找到部门！");
        }
        DynaBean roleBean = metaService.selectOne("JE_RBAC_ROLE",ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID",devRoleId));
        DynaBean dynaBean = new DynaBean("JE_RBAC_ACCOUNTROLE",false);
        dynaBean.set("ACCOUNTROLE_ROLE_ID",devRoleId);
        dynaBean.set("ACCOUNTROLE_ACCOUNT_ID",accountId);
        dynaBean.set("ACCOUNTROLE_ROLE_NAME",roleBean.getStr("ROLE_NAME"));
        dynaBean.set("ACCOUNTROLE_DEPT_ID",accountDeptBeanList.get(0).getStr("ACCOUNTDEPT_DEPT_ID"));
        dynaBean.set("ACCOUNTROLE_DEPT_NAME",accountDeptBeanList.get(0).getStr("ACCOUNTDEPT_DEPT_NAME"));
        commonService.buildModelCreateInfo(dynaBean);
        metaService.insert(dynaBean);
    }

}
